import { useUsers } from "../../hook/users"

import { useResSeckill } from "../../hook/seckill_res"
import { Card, Button, Space, Breadcrumb, Table, Image, Modal, message, Input, Select, Radio, Upload } from 'antd';
import { useEffect, Fragment, useState } from "react"
import _ from "lodash"


import UserApi from "../../api/users"

import { UploadOutlined } from '@ant-design/icons';//使用图标  可以自己切换

import { useHistory } from "react-router-dom"

export const UsersList = () => {

  const [{ rows, curPage, eachPage, total, maxPage, Address }, { getUsers, choseUserCurpage, choseUserEachpage, updataHome, delOneAddress, selectTosever }] = useUsers()

const [poster,setposter]=useState({_id:""})


  const { Option } = Select;
  // 定义

  // 上传头像的按钮信息
  const props = {//props是配置 Upload 组件的参数，
    name: 'file',
    //请求到资源服务器的地址
    action: '/res/users/addphoto',
    headers: {
      authorization: 'authorization-text',
    },
    //data 是自定义需要的一些额外参数
    data: {
      ...poster
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };


  function addPoster (record){
   const token= UserApi.getToken()

   const poster=record.poster?record.poster:""
    setposter({...poster,_id:record._id,token})
  }


  //------------------------------

  const [value, setValue] = useState("")

  function SelectValue(e) {
    setValue(e.target.value)

  }

  async function selectTo() {
    const data = await selectTosever({ name: value })
    message.success(`查询到 ${data.rows.length} 条数据`)
  }


  //------------------------------

  const children = [];
  for (let i = 0; i < Address.length; i++) {
    children.push(<Option key={Address[i]._id}>{Address[i].name}</Option>);
  }
  // 删除收藏的地址

  const [data, setvalue] = useState({ status: false, _id: "" })

  function delAddress(id, addressId) {
    setvalue({ status: true, _id: id, addressId })


  }



  async function delOk() {
    const result = await delOneAddress(data)
    result.ok === 1 ? message.success('删除成功') : message.error("删除失败")

    setvalue({ ...data, status: false })

  }
  function Canceldel() {
    setvalue({ ...data, status: false })
  }


  // 所有使用过的地址
  function allAddressArr(_id, allAddress) {
    let arr = []
    for (let i = 0; i < allAddress.length; i++) {
      arr.push(<Option key={
        allAddress[i]} >
        {
          <Button onClick={() => delAddress(_id, allAddress[i])} style={{ width: "100%" }}>{
            Address.map((item) => {
              if (item._id === allAddress[i]) {
                return item.name
              }
            })
          }</Button>
        }
      </Option>)
    }
    return arr
  }




  const { confirm } = Modal;
  const history = useHistory()


  function deluser() {
    console.log("删除");
  }

  const [addressObj, setaddressObj] = useState(0);
  // 选择自提点
  function choseHome(_id, home, name) {
    setaddressObj({ _id, home, name })
    showModal()
  }

  //--------------------------------------
  const [isModalVisible, setIsModalVisible] = useState(false);
  const showModal = () => {
    setIsModalVisible(true);
  };
  const handleOk = async () => {
    const { _id, home } = addressObj
    await updataHome({ _id, home })
    setIsModalVisible(false);
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };



  //--------------------------------------






  // 页码变化时的函数
  function changpage(Page, each) {

    if (Page != curPage) choseUserCurpage(Page)
    if (each != eachPage) choseUserEachpage(each)

  }


  // 当页面结构加载完成开始请求数据
  useEffect(() => {
    getUsers()
  }, [curPage, eachPage])

  // 列表显示的字段和数据属性名的对应关系
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    }, 
    {
      title: '头像',
      key: 'Poster',
      render: (text, record, index) => {
        const Poster=record.Poster?`/res${record.Poster}`:"/res/users/hema.icon.jfif"
        return <Image  style={{width:"50px"}} src={Poster}/>

      }

    },
    {
      title: '收货地址',
      key: 'home',
      render: (text, record, index) => {
        const { _id, home } = record
        return (
          <Select
            size={"middle"}
            placeholder="请选择收货地址"
            defaultValue={[`${home ? home : "未选择收货地点"}`]}
            onChange={(value, { children }) => choseHome(_id, value, children)}
            style={{ width: '100%' }}
          >
            {children}
          </Select>
        )

      }
    },
    {
      title: '收藏的收获点地址',
      key: 'allAddress',
      render: (text, record, index) => {
        const { _id, allAddress } = record
        return (
          <Select
            size={"middle"}
            bordered={false}
            value={"点击查看所有收货地址"}
            // onChange={(value,{children}) => choseHome(_id, value,children)}
            style={{ width: '100%' }}
          >
            {allAddressArr(_id, allAddress)}
          </Select>
        )

      }
    },
    {
      title: '联系电话',
      dataIndex: 'iphone',
      key: 'iphone',
    },


    {
      title: '操作',
      key: 'zip',
      render: (text, record, index) => {
        return (
          <Fragment>
            {/* <Button  onClick={()=>reviseStudent(_id)}>修改</Button> */}
            <Button danger type="primary" style={{ backgroundColor: "#00BFFF", border: "0", marginLeft: "20px" }} disabled onClick={() => deluser(record)}>删除</Button>
            <Upload {...props}>

              <Button onClick={()=>addPoster(record)} icon={<UploadOutlined  />}>上传头像</Button>
            </Upload>,

          </Fragment>
        )
      }
    },
  ];

  return (
    <Space direction="vertical" style={{ width: "100%" }}>

      <Card >
        <Breadcrumb>
          <Breadcrumb.Item>主页</Breadcrumb.Item>
          <Breadcrumb.Item>
            <a href="/#/info/seckill_list">用户列表</a>
          </Breadcrumb.Item>
        </Breadcrumb>


      </Card>
      <Card >
        {/* <div style={{ marginBottom: "20px", width: "800px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span>查询</span>   <span>开始日期：<DatePicker format={dateFormatday} onChange={onSearch} /></span>
          <span><Input onChange={onSearch1} /> </span>
          <span><Button onClick={() => select()} >查询</Button> </span>
        </div> */}
        <Input style={{ width: "200px", marginBottom: "20px" }} placeholder="输入用户名进行查找" onChange={SelectValue} /><Button onClick={selectTo}>查询</Button>

        <Table rowKey={record => record._id} dataSource={rows} columns={columns}
          pagination={{ current: curPage, total: total, pageSizeOptions: [5, 10, 15,], pageSize: eachPage, defaultPageSize: eachPage, position: ["bottomCenter"], onChange: changpage }}
        />
        <Modal title="是否将该用户的自提点地址切换为" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
          <p>将修改地址为:   {addressObj.name}</p>
        </Modal>
        <Modal title="是否删除这个地址？" visible={data.status} onOk={delOk} onCancel={Canceldel}>
          <p>请谨慎选择！！！</p>
        </Modal>
      </Card>
    </Space>
  )

}